//
//  TrainOrderDetailsController.swift
//  AirTravel
//
//  Created by apple on 2021/8/24.
//

import UIKit
import Moya
import SwiftyJSON
import FWPopupView

protocol TrainOrderDetailsDelegate:NSObjectProtocol {
    func trainOrderDetailsClick()
}

class TrainOrderDetailsController: UIViewController {

    weak var delegate: TrainOrderDetailsDelegate?
    @IBOutlet weak var bottomLine: NSLayoutConstraint!
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var titleLab: UILabel!
    @IBOutlet weak var submitBtn: UIButton!
    @IBOutlet weak var priceLab: UILabel!
    @IBOutlet weak var tabView: UITableView!
    @IBOutlet weak var countdownLab: UILabel!
    let identifyTON = "TrainOrderNumberCell"
    let identifyOP = "OrdersPersonnelCell"
    let identifyCB = "CancelButtonCell"
    let identifyTE = "TicketEndorsedCell"
    let identifyTOI = "TrainOrderInformationCell"
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    var order_id = ""
    var payType = ""
    var dataDic : Dictionary<String,Any>?
    let dateFormatter = DateFormatter()
    /// 5秒点击刷新倒计时
//    let refreshTimer = WMCountDown()
    var type = 0
    var dataStr = ""
    var according = ""
    var difference = "今天"
    var startCity = "成都"
    var endCity = "北京"
//    deinit {
//        refreshTimer.stop()
//    }
    
    lazy var payView: ChoosePayView = {
        let customPopupView = ChoosePayView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 320))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.white
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "0"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    //视图将要显示
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        //设置导航栏背景透明
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(),
                                                                    for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        NotificationCenter.default.addObserver(self, selector: #selector(aliPayClicks), name: Notification.Name("aliPaySucceess"), object: nil)
    }
         
    //视图将要消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //重置导航栏背景
        self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        self.navigationController?.navigationBar.shadowImage = nil
        NotificationCenter.default.removeObserver(self)
        self.delegate?.trainOrderDetailsClick()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.dateFormatter.dateFormat = "yyyy-MM-dd"
        let chinese = Locale.init(identifier: "zh-CN")
        self.dateFormatter.locale = chinese
        self.title = "订单详情"
        self.tabView.layer.cornerRadius = 6
        self.tabView.layer.masksToBounds = true
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.rowHeight = UITableView.automaticDimension
        self.tabView.estimatedRowHeight = 150
        self.tabView.separatorStyle = .none
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "CancelButtonCell", bundle: nil), forCellReuseIdentifier: identifyCB)
        self.tabView.register(UINib.init(nibName: "TrainOrderNumberCell", bundle: nil), forCellReuseIdentifier: identifyTON)
        self.tabView.register(UINib.init(nibName: "OrdersPersonnelCell", bundle: nil), forCellReuseIdentifier: identifyOP)
        self.tabView.register(UINib.init(nibName: "TicketEndorsedCell", bundle: nil), forCellReuseIdentifier: identifyTE)
        self.tabView.register(UINib.init(nibName: "TrainOrderInformationCell", bundle: nil), forCellReuseIdentifier: identifyTOI)
        
        self.submitBtn.layer.cornerRadius = 6
        self.submitBtn.layer.masksToBounds = true
        
        let status = "\(self.dataDic?["status"] ?? "")"
        if let dic = self.dataDic {
            self.order_id = "\(dic["orderId"] ?? "")"
            let orderAmount = "\(dic["orderAmount"] ?? "")"
            self.priceLab.text = "￥\(orderAmount)"
        }
        
        
        
//        self.refreshTimer.countDown = { [weak self] (d, h, m, s) in
//            var time = d + ":" + h + ":" + m + ":" + s
//            if d == "00" {
//                time = h + ":" + m + ":" + s
//            }else if h == "00" {
//                time = m + ":" + s
//            }else if m == "00" {
//                time = s
//            }
//            print(time)
//            if time == "00:00:00" || time == "00:00:0" || time == "00:00"{
//                self?.countdownLab.text = "锁定结束，请重新下单"
//                self?.submitBtn.isHidden = true
//            }else{
//                self?.countdownLab.text = "座位已成功锁定！请在26分37秒内完成支付。"
//                self?.submitBtn.isHidden = false
//            }
//
//        }
        
        self.type = Int(status) ?? 0
        
        switch self.type {
        case 0:
            self.titleLab.text = "占座成功"
            self.countdownLab.text = "座位已成功锁定！请尽快支付"
        case 1:
            self.titleLab.text = "已支付，正在出票"
            self.countdownLab.text = "你的订单正在出票，祝您旅途愉快"
            self.bottomView.isHidden = true
            self.bottomLine.constant = 0
        case 2:
            self.titleLab.text = "占座失败"
            self.countdownLab.text = "您的车票购买失败，请重新购买"
            self.bottomView.isHidden = true
            self.bottomLine.constant = 0
        case 3:
            self.titleLab.text = "已支付，正在出票"
            self.countdownLab.text = "你的订单正在出票，祝您旅途愉快"
            self.bottomView.isHidden = true
            self.bottomLine.constant = 0
        case 4:
            self.titleLab.text = "购票成功"
            self.countdownLab.text = "您的车票已购票成功，祝您旅途愉快"
            self.bottomView.isHidden = true
            self.bottomLine.constant = 0
        case 5:
            self.titleLab.text = "已取消"
            self.countdownLab.text = "你的订单已取消，可重新进行与预定"
            self.bottomView.isHidden = true
            self.bottomLine.constant = 0
        case 6:
            self.titleLab.text = "出行结束"
            self.countdownLab.text = "您出行完成，祝您旅途愉快"
            self.bottomView.isHidden = true
            self.bottomLine.constant = 0
        default:
            self.titleLab.text = "出票失败"
            self.countdownLab.text = "您的车票购买失败，请重新购买"
            self.bottomView.isHidden = true
            self.bottomLine.constant = 0
        }
        
    }
    
    @objc func aliPayClicks(notifi : Notification) {
        
        
        print("11111111111")
        self.navigationController?.popViewController(animated: true)
    }
    //支付
    @IBAction func submit(_ sender: UIButton) {
        self.payView.show()
    }
    
    //订单支付接口地址
    func orderPay() {
        cancelableRequest = NetWorkRequest(API1.orderPay(parameters: ["order_id":self.order_id,"method":"app"]), completion: {[weak self] (responseString) -> (Void) in
            if self?.payType == "4"{
                //调起微信支付
                let req = PayReq.init()
                req.partnerId = "\(responseString["data"]["partnerid"])"
                req.prepayId = "\(responseString["data"]["prepayid"])"
                req.nonceStr = "\(responseString["data"]["noncestr"])"
                req.timeStamp = UInt32("\(responseString["data"]["timestamp"])") ?? 0
                req.package = "\(responseString["data"]["package"])"
                req.sign = "\(responseString["data"]["sign"])"
                WXApi.send(req, completion: nil)
            }else{
                //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
                let appScheme = "AirTravel"
                
                // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
                let orderString = responseString["data"].stringValue
                
                // NOTE: 调用支付结果开始支付
                AlipaySDK.defaultService()?.payOrder(orderString, fromScheme: appScheme, callback: { (resultDic) in
                    
                    print("afafa")
                })
            }
            
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    //明细
    @IBAction func detailBtn(_ sender: Any) {
    }
    //取消订单
    func orderCancel() {
        cancelableRequest = NetWorkRequest(API1.orderCancel(parameters: ["order_id":self.order_id]), completion: {[weak self] (responseString) -> (Void) in
            YProgressHUD.showToast("取消订单成功")
            self?.navigationController?.popViewController(animated: true)
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
}

extension TrainOrderDetailsController:UITableViewDataSource,UITableViewDelegate{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.type == 4{
            return 4
        }
        return 3
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            if let dic = self.dataDic {
                let order_passenger = dic["order_passenger"] as? Array<Any>
                guard let array = order_passenger else { return 0 }
                return array.count
            }
            return 0
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyTON) as! TrainOrderNumberCell
            cell.selectionStyle = .none
            if let dic = self.dataDic {
                cell.end_hoursLab.text = "\(dic["arriveTime"] ?? "")"
                cell.end_dateOfLab.text = "\(dic["arriveDate"] ?? "")"
                cell.start_hoursLab.text = "\(dic["departTime"] ?? "")"
                cell.start_dateOfLab.text = "\(dic["departDate"] ?? "")"
                cell.trainsLab.text = "\(dic["trainNo"] ?? "")"
                cell.journey_timeLab.text = "\(dic["useTime"] ?? "")"
                cell.start_standingLab.text = "\(dic["fromStationName"] ?? "")"
                cell.terminalLab.text = "\(dic["toStationName"] ?? "")"
                cell.orderNumberLab.text = "订单号:\(dic["orderId"] ?? "")"
            }
            return cell
        case 2:
            switch self.type {
            case 0:
                let cell = tableView.dequeueReusableCell(withIdentifier: identifyCB) as! CancelButtonCell
                cell.selectionStyle = .none
                return cell
            case 4:
                let cell = tableView.dequeueReusableCell(withIdentifier: identifyTE) as! TicketEndorsedCell
                cell.selectionStyle = .none
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: identifyTOI) as! TrainOrderInformationCell
                cell.selectionStyle = .none
                return cell
            }
        case 3:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyTOI) as! TrainOrderInformationCell
            cell.selectionStyle = .none
            if let dic = self.dataDic {
                cell.contentLab.text = "创建时间:\(dic["createTime"] ?? "")\n支付方式:\(dic["payTypeName"] ?? "")"
            }
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyOP) as! OrdersPersonnelCell
            cell.selectionStyle = .none
            cell.refundBtn.tag = indexPath.row
            cell.endorseBtn.tag = indexPath.row
            
            switch self.type {
            case 4:
                cell.refundBtn.isHidden = false
                cell.endorseBtn.isHidden = false
                cell.refundBtn.addTarget(self, action: #selector(refund(sender:)), for: .touchUpInside)
                cell.endorseBtn.addTarget(self, action: #selector(endorse(sender:)), for: .touchUpInside)
            default:
                cell.refundBtn.isHidden = true
                cell.endorseBtn.isHidden = true
            }
            if let dic = self.dataDic {
                let order_passenger = dic["order_passenger"] as? Array<Any>
                guard let array = order_passenger else { return cell }
                let dict = array[indexPath.row] as? Dictionary<String,Any>
                cell.nameLab.text = "\(dict?["name"] ?? "")"
                cell.idCardLab.text = "身份证 \(dict?["number"] ?? "")"
                cell.seatLab.text = "\(dic["seatName"] ?? "") ￥\(dic["ticketPrice"] ?? "")"
                cell.carriageLab.text = "\(dict?["carriageNo"] ?? "")车厢\(dict?["seatNo"] ?? "")"
                cell.paymentStatusLab.text = "\(dic["statusName"] ?? "")"
                let changeInfo = dict?["changeInfo"] as? Dictionary<String,Any>
                if let change = changeInfo {
                    cell.seatLab.textColor = UIColor.init(hexString: "666666")
                    cell.carriageLab.textColor = UIColor.init(hexString: "666666")
                    cell.topLine.constant = 120
                    cell.topView.isHidden = false
                    let dateFormatter1 = DateFormatter()
                    dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss"
                    
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "yyyy-MM-dd"
                    let changeArriveTime = "\(change["changeArriveTime"] ?? "")"
                    let arriveTimeDate = dateFormatter1.date(from: changeArriveTime) ?? Date()
                    let arriveDate = dateFormatter.string(from: arriveTimeDate)
                    cell.end_dateOfLab.text = arriveDate
                    
                    let changeDepartTime = "\(change["changeDepartTime"] ?? "")"
                    let departDateDate = dateFormatter1.date(from: changeDepartTime) ?? Date()
                    let departDate = dateFormatter.string(from: departDateDate)
                    cell.start_dateOfLab.text = departDate
                    
                    dateFormatter.dateFormat = "HH:mm"
                    let arriveTimeDate1 = dateFormatter1.date(from: changeArriveTime) ?? Date()
                    let arriveTime = dateFormatter.string(from: arriveTimeDate1)
                    cell.end_hoursLab.text = arriveTime
                    
                    let departDateDate1 = dateFormatter1.date(from: changeDepartTime) ?? Date()
                    let departTime = dateFormatter.string(from: departDateDate1)
                    cell.start_hoursLab.text = departTime
                    
                    cell.trainsLab.text = "\(change["changeTrainNo"] ?? "")"
                    cell.journey_timeLab.isHidden = true
                    cell.start_standingLab.text = "\(change["changeFromStationName"] ?? "")"
                    cell.terminalLab.text = "\(change["changeToStationName"] ?? "")"
                    cell.seatNameLab.text = "\(change["changeSeatName"] ?? "") ￥\(change["changeTicketPrice"] ?? "")"
                    cell.changeCarriageNoLab.text = "\(change["changeCarriageNo"] ?? "")车厢\(change["changeSeatNo"] ?? "")"
                    
                    let changeStatus = "\(change["changeStatus"] ?? "")"
                    if changeStatus == "1" || changeStatus == "0"{
                        cell.refundBtn.isUserInteractionEnabled = true
                        cell.endorseBtn.isUserInteractionEnabled = true
                        cell.refundBtn.layer.cornerRadius = 6
                        cell.refundBtn.layer.borderWidth = 1
                        cell.refundBtn.layer.borderColor = Blue_COLOR.cgColor
                        cell.refundBtn.setTitleColor(Blue_COLOR, for: .normal)
                        
                        cell.endorseBtn.layer.cornerRadius = 6
                        cell.endorseBtn.layer.borderWidth = 1
                        cell.endorseBtn.layer.borderColor = Blue_COLOR.cgColor
                        cell.endorseBtn.setTitleColor(Blue_COLOR, for: .normal)
                        if changeStatus == "1" {
                            cell.paymentStatusLab.text = "改签中"
                        }
                    }else {
                        if changeStatus == "2" {
                            cell.paymentStatusLab.text = "改签成功"
                        }else if changeStatus == "3"{
                            cell.paymentStatusLab.text = "改签失败"
                        }
                        cell.endorseBtn.isUserInteractionEnabled = false
                        cell.refundBtn.layer.cornerRadius = 6
                        cell.refundBtn.layer.borderWidth = 1
                        cell.refundBtn.layer.borderColor = Blue_COLOR.cgColor
                        cell.refundBtn.setTitleColor(Blue_COLOR, for: .normal)
                        
                        cell.endorseBtn.layer.cornerRadius = 6
                        cell.endorseBtn.layer.borderWidth = 1
                        cell.endorseBtn.layer.borderColor = UIColor.init(hexString: "666666").cgColor
                        cell.endorseBtn.setTitleColor(UIColor.init(hexString: "666666"), for: .normal)
                    }
                    let refundInfo = dict?["refundInfo"] as? Dictionary<String,Any>
                    if let refund = refundInfo {
                        let refundStatus = "\(refund["refundStatus"] ?? "")"
                        if refundStatus == "0" {
                            
                        }else{
                            if refundStatus == "1" {
                                cell.paymentStatusLab.text = "退票中"
                            }else if refundStatus == "2"{
                                cell.paymentStatusLab.text = "退票成功"
                            }else if refundStatus == "3"{
                                cell.paymentStatusLab.text = "退票失败"
                            }
                            cell.endorseBtn.isUserInteractionEnabled = false
                            cell.refundBtn.isUserInteractionEnabled = false
                            cell.refundBtn.layer.cornerRadius = 6
                            cell.refundBtn.layer.borderWidth = 1
                            cell.refundBtn.layer.borderColor = UIColor.init(hexString: "666666").cgColor
                            cell.refundBtn.setTitleColor(UIColor.init(hexString: "666666"), for: .normal)
                            
                            cell.endorseBtn.layer.cornerRadius = 6
                            cell.endorseBtn.layer.borderWidth = 1
                            cell.endorseBtn.layer.borderColor = UIColor.init(hexString: "666666").cgColor
                            cell.endorseBtn.setTitleColor(UIColor.init(hexString: "666666"), for: .normal)
                        }
                    }
                    
                }else{
                    cell.topLine.constant = 0
                    cell.topView.isHidden = true
                }
                
            }
            return cell
            
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        switch indexPath.section {
        case 0:
            return 170
        case 2:
            if self.type == 0 {
                return 45
            }
            if self.type == 4{
                return 61
            }
            return UITableView.automaticDimension
        case 3:
            return UITableView.automaticDimension
        default:
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        if section == 0 {
            return 0
        }
        return 5
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        let footview = UIView.init()
        footview.backgroundColor = UIColor.groupTableViewBackground
        return footview
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if indexPath.section == 2 {
            switch self.type {
            case 0://取消订单
                self.orderCancel()
            case 2:
                break
            default:
                break
            }
        }
    }
    //退票
    @objc func refund(sender:UIButton) {
        if let dic = self.dataDic {
            let order_passenger = dic["order_passenger"] as? Array<Any>
            guard let array = order_passenger else { return }
            let dict = array[sender.tag] as? Dictionary<String,Any>
            let vc = TrainRefundAController()
            vc.dataDic = self.dataDic
            vc.seatDic = dict
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    //改签
    @objc func endorse(sender:UIButton) {
        if let dic = self.dataDic {
            UserDefaults.standard.setValue("\(dic["orderId"] ?? "")", forKey: "xn_order_id")
            UserDefaults.standard.setValue("\(dic["contactMobile"] ?? "")", forKey: "xn_contactMobile")
            UserDefaults.standard.setValue("\(dic["departDate"] ?? "")", forKey: "xn_departDate")
            UserDefaults.standard.setValue("\(dic["arriveDate"] ?? "")", forKey: "xn_arriveDate")
            UserDefaults.standard.setValue("\(dic["departTime"] ?? "")", forKey: "xn_departTime")
            UserDefaults.standard.setValue("\(dic["arriveTime"] ?? "")", forKey: "xn_arriveTime")
            UserDefaults.standard.setValue("\(dic["fromStationName"] ?? "")", forKey: "xn_fromStationName")
            UserDefaults.standard.setValue("\(dic["toStationName"] ?? "")", forKey: "xn_toStationName")
            UserDefaults.standard.setValue("\(dic["trainNo"] ?? "")", forKey: "xn_trainNo")
            UserDefaults.standard.setValue("\(dic["useTime"] ?? "")", forKey: "xn_useTime")
            let order_passenger = dic["order_passenger"] as? Array<Any>
            if let array = order_passenger {
                let dict = array[sender.tag] as? Dictionary<String,Any>
                UserDefaults.standard.setValue("\(dict?["ps_id"] ?? "")", forKey: "xn_ps_id")
                UserDefaults.standard.setValue("\(dict?["name"] ?? "")", forKey: "xn_name")
                UserDefaults.standard.setValue("\(dict?["number"] ?? "")", forKey: "xn_number")
                UserDefaults.standard.setValue("\(dict?["ticketAmount"] ?? "")", forKey: "xn_ticketAmount")
            }
            self.processingDate()
        }else{
            YProgressHUD.showToast("数据异常,请退出重试")
        }
        
    }
    
    func processingDate() {
        if let dic = self.dataDic {
            self.dataStr = "\(dic["departDate"] ?? "")"
            self.startCity = "\(dic["fromStationName"] ?? "")"
            self.endCity = "\(dic["toStationName"] ?? "")"
            let date = self.dateFormatter.date(from: self.dataStr)
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "MM月dd日"
            let according = dateFormatter.string(from: date ?? Date())
            
            dateFormatter.dateFormat = "yyyy-MM-dd"
            let jtStr = dateFormatter.string(from: Date())
            guard let date1 = dateFormatter.date(from: jtStr) else { return }
            
            let components = NSCalendar.current.dateComponents([.day], from: date1, to: date ?? Date())
            
            let components1 = NSCalendar.current.dateComponents([.weekday], from: date ?? Date())
            
            var difference = ""
            if components.day == 0{
                difference = "今天"
            }else if components.day == 1 {
                difference = "明天"
            }else{
                switch components1.weekday {
                case 1:
                    difference = "周日"
                case 2:
                    difference = "周一"
                case 3:
                    difference = "周二"
                case 4:
                    difference = "周三"
                case 5:
                    difference = "周四"
                case 6:
                    difference = "周五"
                case 7:
                    difference = "周六"
                default:
                    break
                }
            }
            
            self.according = according
            self.difference = difference
            
            let vc = TrainBeenChangedController()
            vc.according = self.according
            vc.difference = self.difference
            vc.dataStr = self.dataStr
            vc.fromStationName = self.startCity
            vc.toStationName = self.endCity
            vc.type = 1
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
}

extension TrainOrderDetailsController:ChoosePayDelegate{
    func choosePayClick(data: Dictionary<String, Any>) {
        self.payView.hide()
        self.payView.hideKeyboard()
        let key = "\(data["key"] ?? "")"
        self.payType = key
        self.orderPay()
    }
}
